<template>
  <div class="in-wrap">
    <!-- 公共头引入 -->
    <header id="header">
      <section class="container">
        <h1 id="logo">
          <nuxt-link to="/">
            <img src="~/assets/img/logo-long.png" alt="CodeEdu"/>
          </nuxt-link>
        </h1>
        <div class="h-r-nsl">
          <ul class="nav">
            <nuxt-link to="/" tag="li" active-class="current" exact>
              <a>首页</a>
            </nuxt-link>
            <nuxt-link to="/course" tag="li" active-class="current">
              <a>课程</a>
            </nuxt-link>
            <nuxt-link to="/teacher" tag="li" active-class="current">
              <a>名师</a>
            </nuxt-link>
            <nuxt-link to="/article" tag="li" active-class="current">
              <a>文章</a>
            </nuxt-link>
            <nuxt-link to="/qa" tag="li" active-class="current">
              <a>团队</a>
            </nuxt-link>
          </ul>
          <!-- / nav -->
          <ul class="h-r-login">
            <li v-show="!loginInfo.id" id="no-login">
              <nuxt-link to="/login" title="登录">
                <em class="icon18 login-icon">&nbsp;</em>
                <span class="vam ml5">登录</span>
              </nuxt-link>
              <nuxt-link to="/register" title="注册">
                <span class="vam ml5">注册</span>
              </nuxt-link>
            </li>

            <li v-show="loginInfo.id" id="is-login-one" class="mr10">
              <!-- 新增下拉菜单的消息菜单 -->
<!--              <el-dropdown>-->
<!--                <span class="el-dropdown-link">-->

<!--                    <span class="el-dropdown-link">-->
<!--                  <el-badge>-->
<!--                     <el-button-->
<!--                       style="font-size: 1.5em"-->
<!--                       type="text"-->
<!--                       @click="myHistoryInfo"-->
<!--                     >-->
<!--                      <i class="el-icon-time"></i>-->
<!--                    </el-button>-->
<!--                  </el-badge>-->
<!--                </span>-->
<!--                </span>-->
<!--              </el-dropdown>-->
<!--              &nbsp;&nbsp;&nbsp;&nbsp;-->
<!--              <el-dropdown>-->
<!--                <span class="el-dropdown-link">-->
<!--                  <el-badge-->
<!--                    :value="messageCount"-->
<!--                    :max="99"-->
<!--                    :hidden="messageCount === 0"-->
<!--                  >-->
<!--                    <el-button-->
<!--                      style="font-size: 1.5em"-->
<!--                      type="text"-->
<!--                      @click="myMessageInfo"-->
<!--                    >-->
<!--                      <i class="el-icon-chat-dot-round"></i>-->
<!--                    </el-button>-->
<!--                  </el-badge>-->
<!--                </span>-->
<!--                <el-dropdown-menu slot="dropdown">-->
<!--                  <el-dropdown-item-->
<!--                    v-for="item in unReadMessage"-->
<!--                    :key="item.id"-->
<!--                  >-->
<!--                    <nuxt-link-->
<!--                      style="text-decoration: none"-->
<!--                      v-show="item.type == 0 || item.type == 2"-->
<!--                      :to="'/article/' + item.link"-->
<!--                    >-->
<!--                      <span style="color: #2d9aff">{{ item.senderName }}</span>-->
<!--                      <span v-show="item.type == 0"> 新增了评论</span>-->
<!--                      <span v-show="item.type == 1"> 回复了评论</span>-->
<!--                      <span v-show="item.type == 2"> 点赞了文章</span>-->
<!--                      <span>{{ item.content }}</span>-->
<!--                    </nuxt-link>-->
<!--                  </el-dropdown-item>-->
<!--                  <el-dropdown-item style="text-align: center">-->
<!--                    <span>-->
<!--                      <el-button-->
<!--                        type="text"-->
<!--                        size="default"-->
<!--                        @click="myMessageInfo"-->
<!--                      >查看更多-->
<!--                        <i class="el-icon-arrow-right"></i>-->
<!--                      </el-button>-->
<!--                    </span>-->
<!--                  </el-dropdown-item>-->
<!--                </el-dropdown-menu>-->
<!--              </el-dropdown>-->
              <!-- <el-badge v-show="messageCount == 0" class="item">
                <el-button @click="myMessageInfo"
                  ><em class="icon18 news-icon"></em
                ></el-button>
              </el-badge> -->
              &nbsp;&nbsp;&nbsp;&nbsp;
              <el-dropdown>
                <nuxt-link to="/">
                  <img
                    :src="loginInfo.avatar"
                    width="30"
                    height="30"
                    class="vam picImg"
                    alt/>
                  <span id="userName" class="vam disIb">{{
                      loginInfo.nickname
                    }}</span>
                  <i class="el-icon-arrow-down el-icon--right"></i
                  ></nuxt-link>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="editInfo" icon="el-icon-user"
                  >编辑信息
                  </el-dropdown-item>
                  <el-dropdown-item
                    @click.native="myArticleInfo"
                    icon="el-icon-notebook-1"
                  >我的文章
                  </el-dropdown-item>
                  <el-dropdown-item
                    @click.native="myCourseInfo"
                    icon="el-icon-reading"
                  >我的课程
                  </el-dropdown-item>
                  <el-dropdown-item
                    @click.native="changePwd"
                    icon="el-icon-setting"
                  >修改密码
                  </el-dropdown-item>
                  <el-dropdown-item
                    @click.native="logout"
                    icon="el-icon-switch-button"
                  >退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-dropdown>
                <span class="el-dropdown-link">
                  <el-badge
                    :value="messageCount"
                    :max="99"
                    :hidden="messageCount === 0"
                  >
                    <el-button
                      style="font-size: 1.5em"
                      type="text"
                      @click="myMessageInfo"
                    >
                      <i class="el-icon-chat-dot-round"></i>
                    </el-button>
                  </el-badge>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-for="item in unReadMessage"
                    :key="item.id"
                  >
                    <nuxt-link
                      style="text-decoration: none"
                      v-show="item.type == 0 || item.type == 2"
                      :to="'/article/' + item.link"
                    >
                      <span style="color: #2d9aff">{{ item.senderName }}</span>
                      <span v-show="item.type == 0"> 新增了评论</span>
                      <span v-show="item.type == 1"> 回复了评论</span>
                      <span v-show="item.type == 2"> 点赞了文章</span>
                      <span>{{ item.content }}</span>
                    </nuxt-link>
                  </el-dropdown-item>
                  <el-dropdown-item style="text-align: center">
                    <span>
                      <el-button
                        type="text"
                        size="default"
                        @click="myMessageInfo"
                      >查看更多
                        <i class="el-icon-arrow-right"></i>
                      </el-button>
                    </span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

            </li>
          </ul>
          <aside class="h-r-search">
            <form action="#" method="post">
              <el-autocomplete
                prefix-icon="el-icon-search"
                v-model="state"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入内容"
                value-key="title"
                @select="handleSelect"
                suffix="el-icon-search"
              >
              </el-autocomplete>
            </form>
          </aside>
        </div>
        <aside class="mw-nav-btn">
          <div class="mw-nav-icon"></div>
        </aside>
        <div class="clear"></div>
      </section>
    </header>

    <!-- /公共头引入 -->
    <nuxt />

    <!-- 公共底引入 -->
    <footer id="footer">
      <section class="container">
        <div class>
          <h4 class="hLh30">
            <span class="fsize18 f-fM c-999">友情链接-项目地址</span>
          </h4>
          <ul class="of flink-list">
            <li>
              <a
                href="https://gitee.com/jzhmcoo1/code_edu_ui"
                title="CodeEDU前台地址"
                target="_blank"
              >CodeEdu前台前端项目地址</a
              >
            </li>
            <li>
              <a
                href="https://gitee.com/paradox_hyw/code_edu-vue"
                title="CodeEDU前台地址"
                target="_blank"
              >CodeEdu后台前端项目地址</a
              >
            </li>
            <li>
              <a
                href="https://gitee.com/paradox_hyw/code_edu"
                title="CodeEDU后端地址"
                target="_blank"
              >CodeEdu后端项目地址</a
              >
            </li>
          </ul>
          <div class="clear"></div>
        </div>
        <div class="b-foot">
          <section class="fl col-7">
            <section class="mr20">
              <section class="b-f-link">
                <a href="#" title="关于我们" target="_blank">关于我们</a>|
                <a href="#" title="联系我们" target="_blank">联系我们</a>|
                <a href="#" title="帮助中心" target="_blank">帮助中心</a>|
                <a href="#" title="资源下载" target="_blank">资源下载</a>|
                <span>服务热线：xx(上海) </span>
                <span>Email：xx</span>
              </section>
              <section class="b-f-link mt10">
                <span>©2021课程版权均归dhu所有 沪ICP备xx号</span>
              </section>
            </section>
          </section>
          <aside class="fl col-3 tac mt15">
            <section class="gf-tx">
              <span>
                <img src="~/assets/img/wx-icon.png" alt/>
              </span>
            </section>
            <section class="gf-tx">
              <span>
                <img src="~/assets/img/wb-icon.png" alt/>
              </span>
            </section>
          </aside>
          <div class="clear"></div>
        </div>
      </section>
    </footer>
    <!-- /公共底引入 -->
  </div>
</template>
<script>
import "~/assets/css/reset.css";
import "~/assets/css/theme.less";
import "~/assets/css/global.css";
import "~/assets/css/web.css";
import cookie from "js-cookie";
import login from "@/api/login";
import messageApi from "@/api/message";
import course from "../api/course";

export default {
  data() {
    return {
      input: "",
      token: "",
      unRead: false,
      messageCount: 0,
      unReadMessage: {},
      loginInfo: {
        id: "",
        age: "",
        avatar: "",
        mobile: "",
        nickname: "",
        sex: "",
      },
      state: "",
      timeout: null,
    };
  },

  created() {
    this.token = this.$route.query.token;
    console.log(this.$route.query.token);
    if (this.token) {
      this.wxLogin();
    }
    //获取路径的token值
    this.showInfo();
  },
  // beforeDestroy () {
  //   this.onbeforeunload()
  // },
  methods: {
    conectWebSocket() {
      // WebSocket
      if ("WebSocket" in window) {
        this.websocket = new WebSocket(
          "ws://127.0.0.1:8222/websocket/" + this.loginInfo.id
        // "ws://106.15.109.151:8222/websocket/" + this.loginInfo.id
        );
        this.initWebSocket();
      } else {
        alert("当前浏览器 Not support websocket");
      }
    },
    initWebSocket() {
      // 连接错误
      this.websocket.onerror = this.setErrorMessage;

      // 连接成功
      this.websocket.onopen = this.setOnopenMessage;

      // 收到消息的回调
      this.websocket.onmessage = this.setOnmessageMessage;

      // 连接关闭的回调
      this.websocket.onclose = this.setOncloseMessage;

      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = this.onbeforeunload;
    },
    setErrorMessage() {
      console.log(
        "WebSocket连接发生错误   状态码：" + this.websocket.readyState
      );
    },
    setOnopenMessage() {
      console.log("WebSocket连接成功    状态码：" + this.websocket.readyState);
    },
    setOnmessageMessage(event) {
      // 根据服务器推送的消息做自己的业务处理
      console.log("服务端返回：" + event.data);
      messageApi.checkUnRead().then((response) => {
        this.messageCount = response.data.data.count;
        this.unReadMessage = response.data.data.unReadMessage;
        console.log("msgCount"+this.messageCount)
      });

    },
    setOncloseMessage() {
      console.log("WebSocket连接关闭    状态码：" + this.websocket.readyState);
    },
    onbeforeunload() {
      this.closeWebSocket();
    },
    closeWebSocket() {
      this.websocket.close();
    },

    checkUnRead() {
      messageApi.checkUnRead().then((response) => {
        this.unRead = response.data.data.unRead;
        this.messageCount = response.data.data.count;
        this.unReadMessage = response.data.data.unReadMessage;
      });
    },

    //创建方法，从cookie获取用户信息
    showInfo() {
      //从cookie获取用户信息
      var userStr = cookie.get("dhu_ucenter");
      // 把字符串转换json对象(js对象)
      if (userStr) {
        this.loginInfo = JSON.parse(userStr);
        this.conectWebSocket();
        this.checkUnRead();
      }
    },
    logout() {
      cookie.remove("dhu_token");
      cookie.remove("dhu_ucenter");
      this.onbeforeunload();
      window.location.href = "/";
    },
    wxLogin() {
      if (this.token === "") return;
      //把token存在cookie中、也可以放在localStorage中
      cookie.set("dhu_token", this.token);
      cookie.set("dhu_ucenter", "");
      //登录成功根据token获取用户信息
      login.getLoginUserInfo().then((response) => {
        this.loginInfo = response.data.data.userInfo;
        //将用户信息记录cookie
        cookie.set("dhu_ucenter", this.loginInfo);
      });
    },
    myHistoryInfo() {
      this.$router.push("/ucenter/myHistory/"+this.loginInfo.id);
    },
    myMessageInfo() {
      this.unRead = false;
      this.messageCount = 0;
      this.unReadMessage = {};
      this.$router.push("/ucenter/myMessage/" + this.loginInfo.id);
    },
    editInfo() {
      this.$router.push("/ucenter/" + this.loginInfo.id);
    },
    myCourseInfo() {
      this.$router.push("/ucenter/myCourse/" + this.loginInfo.id);
    },
    myArticleInfo() {
      this.$router.push("/article/myArticle/" + this.loginInfo.id);
    },
    changePwd() {
      this.$router.push("/changePassword");
    },
    querySearchAsync(queryString, cb) {
      let results = {};
      if (queryString !== "" || queryString !== null) {
        course.suggestSuggest(queryString).then((response) => {
          results = response.data.data.courses;
        });
      }
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1000 * Math.random());
    },
    handleSelect(item) {
      //this.$router.push("/course/" + item.id);
      let router_path = this.$route.path;
      if (router_path === "/searchResult/") {
        location.replace("/searchResult/?keyword=" + item.title);
      } else {
        this.$router.push({
          path: "/searchResult/",
          query: {
            keyword: item.title,
          },
        });
      }
    },
  },
};
</script>

<style lang="less">
.el-input__inner {
  border-radius: 20px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}

.el-icon-arrow-down {
  font-size: 12px;
}
</style>
